<template>
	<view class="root">
		<dialog-shell ref="add_shell" title="添加类别" @confirm="confirmAdd">
			<view style="margin: 20rpx;">
				<input type="text" placeholder="请输入昵称" focus style="padding-left: 15rpx;" v-model="newName">
			</view>
		</dialog-shell>
		<dialog-shell ref="update_shell" title="修改类别" @confirm="confirmUpdate">
			<view style="margin: 20rpx;">
				<input type="text" placeholder="请输入昵称" focus style="padding-left: 15rpx;" v-model="oldName">
			</view>
		</dialog-shell>

		<dialog-shell ref="add_tag_shell" title="添加标签" @confirm="confirmAddTag">
			<view style="margin: 20rpx;">
				<input type="text" placeholder="请输入昵称" focus style="padding-left: 15rpx;" v-model="newNameTag">
			</view>
		</dialog-shell>
		<dialog-shell ref="update_tag_shell" title="修改标签" @confirm="confirmUpdateTag">
			<view style="margin: 20rpx;">
				<input type="text" placeholder="请输入昵称" focus style="padding-left: 15rpx;" v-model="oldNameTag">
			</view>
		</dialog-shell>

		<login-shell ref="login" @after="afterLogin"></login-shell>
		<view class="pro" @click="clickLogin">
			<view class="avatar">
				<image class="avatar" :src='avatar' mode=""></image>
			</view>
			<view class="title">
				<view class="top">
					<text class="size">{{name}}</text>
					<text class="role">{{role}}</text>
					<image v-if="token" class="type" :src="badge" mode=""></image>
				</view>
				<text v-if="token" class="iconfont icon-zhuxiao logout" @click="clickLogout"></text>

				<view style="background-color: black; width: 100%; height: 0.1rpx;"></view>
				<text class="email">{{email}}</text>
			</view>

		</view>
		<view class="data-container" v-if="token">
			<view class="data-title" @click="clickSwitch(0)">
				<text class="data-title-name">我发布的博客 {{myCount}} 篇</text>
				<text :class="status[0].visible ? 'iconfont icon-xiangshang':'iconfont icon-xiangxia1'"></text>
			</view>
			<scroll-view v-if="status[0].visible" scroll-x class="scroll" scroll-with-animation
				@scrolltolower="getMyBlogs()">
				<view v-for="(blog,index) in myBlogs" :key="'m_' +blog.id" class="scroll-item"
					@click="toDetail(blog.id)">
					<image :src="host + blog.picture" mode=""></image>
					<text>{{blog.title}}</text>
				</view>

			</scroll-view>
		</view>

		<view class="data-container" v-if="token">
			<view class="data-title" @click="clickSwitch(2)">
				<text class="data-title-name">我点赞的博客 {{goodCount}} 篇</text>
				<text :class="status[2].visible ? 'iconfont icon-xiangshang':'iconfont icon-xiangxia1'"
					class="icon"></text>
			</view>
			<scroll-view v-if="status[2].visible" scroll-x class="scroll" scroll-with-animation>
				<view v-for="(blog,index) in myGoodsBlogs" :key="'g_' +blog.id" class="scroll-item"
					@click="toDetail(blog.id)">
					<image :src="host + blog.picture" mode=""></image>
					<text>{{blog.title}}</text>
				</view>
			</scroll-view>
		</view>

		<view class="data-container" v-if="token">
			<view class="data-title" @click.stop="clickSwitch(1)">
				<text class="data-title-name">分类 {{categories.length}} 个</text>
				<text :class="status[1].visible ? 'iconfont icon-xiangshang':'iconfont icon-xiangxia1'"
					class="icon"></text>
			</view>
			<view v-if="status[1].visible" class="category-cont">

				<text class="category" v-for="(item,index) in categories" @click.stop="clickUpdate(item.id,item.name)">
					<text class="category-left">{{item.name}}</text>
					<text :class="item.count > 0 ?'category-right':'category-right-del'"
						@click.stop="clickDelete(item.count,item.id,0)">
						{{item.count>0 ?item.count:"X"}}
					</text>
				</text>
				<text class="iconfont icon-tianjia add" @click="clickAddName()"></text>
			</view>
		</view>

		<view class="data-container" v-if="token">
			<view class="data-title" @click.stop="clickSwitch(2)">
				<text class="data-title-name">标签 {{myTags.length}} 个</text>
				<text :class="status[2].visible ? 'iconfont icon-xiangshang':'iconfont icon-xiangxia1'"
					class="icon"></text>
			</view>
			<view v-if="status[2].visible" class="category-cont">
				<text class="category" v-for="(item,index) in myTags" @click.stop="clickUpdateTag(item.id,item.name)">
					<text class="category-left">{{item.name}}</text>
					<text :class="item.count > 0 ?'category-right':'category-right-del'"
						@click.stop="clickDelete(item.count,item.id,1)">
						{{item.count>0 ?item.count:"X"}}
					</text>
				</text>
				<text class="iconfont icon-tianjia add" @click="clickAddNameTag()"></text>
			</view>
		</view>
	</view>
</template>

<script>
	let user = {}
	let page = 0
	let good = []
	let updateTagId = ''
	let categoriess = 'categories'
	let cate = null
	let num = 0
	let updateId = ''
	export default {
		data() {
			return {
				name: "点击登录",
				avatar: "../../static/icons/ic_mine.png",
				host: this.$params.host,
				email: "",
				token: null,
				type: -1,
				badge: "../../static/icons/badge2.png",
				role: "游客",
				goodCount: -1,
				categories: [],
				myBlogs: [],
				myGoodsBlogs: [],
				myCount: -1,
				myTags: [],
				newName: "",
				oldName: "",
				newNameTag: "",
				oldNameTag: "",
				status: [{
					visible: false
				}, {
					visible: false
				}, {
					visible: false
				}, {
					visible: false
				}],

			}
		},
		onLoad() {
			this.$notification.addNotification(this.$params.noti_refresh_user, this.afterLogin, this)
			this.$notification.addNotification(this.$params.noti_refresh_good, this.notificationRefreshGood, this)
			user = uni.getStorageSync(this.$params.user)
			good = uni.getStorageSync(this.$params.key_goods)
			this.token = user.token
			if (this.token) {
				this.avatar = this.host + user.avatar
				this.name = user.nickName
				this.email = user.email
				this.type = user.type

				if (this.type == 0) {
					this.role = "管理员"
					this.badge = "../../static/icons/badge0.png"
				} else if (this.type == 1) {
					this.role = "认证博主"
					this.badge = "../../static/icons/badge1.png"
				} else if (this.type == 2) {
					this.role = "博客会员"
					this.badge = "../../static/icons/badge2.png"
				}
			}
		},
		onUnload() {
			this.$notification.removeNotification(this.$params.noti_refresh_user, this)
			this.$notification.removeNotification(this.$params.noti_refresh_good, this)
		},
		onShow() {
			this.loadData()
		},
		methods: {

			notificationRefreshGood(info) {
				let blog_ids = uni.getStorageSync(this.$params.key_goods)
				good = blog_ids
				this.myGoodsBlogs = []
			},
			toDetail(id) {
				uni.navigateTo({
					url: '../blog/blog?id=' + id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			loadData() {
				if (!this.token) {
					return
				}
				this.myBlogs = []
				this.myCount = -1
				page = 0
				this.getMyBlogs()
				this.getMyGoods()
				this.getCategories()
				this.getTags()
			},
			getMyBlogs() {

				if (this.myCount >= 0 && this.myBlogs.length == this.myCount) {
					return
				}
				let header = {
					"content-type": this.$params.content_type, // 内容类型
					"page": page++, // 当前页数
					"size": 2 // 每页数量
				}
				let url = this.$params.host + 'api/v1/blogs/user/' + user.id
				this.$request.getWithHeader(url, header, res => {
					this.myBlogs = this.myBlogs.concat(res.data)
					this.myCount = parseInt(res.message)
					this.status[0].visible = this.myCount > 0
				}, () => {}, () => {})
			},
			async getMyGoods() {
				const good = uni.getStorageSync(this.$params.key_goods);
				this.myGoodsBlogs = [];
				for (const goods of good) {
					try {
						const res = await this.$request.requestAsync(this.host + 'api/v1/blogs/' + goods);
						this.myGoodsBlogs = this.myGoodsBlogs.concat(res.data.data);
					} catch (err) {
						console.error(err);
					}
				}

				this.goodCount = good.length;
				this.status[2].visible = this.goodCount > 0;
			},

			getCategories() {
				cate = uni.getStorageSync(categoriess)
				if (!cate) {
					this.$request.get(this.host + 'api/v1/categories/', res => {
						uni.setStorageSync(categoriess, res.data)
						this.getCategoriesCount(res.data)
					})
				} else {
					this.getCategoriesCount(cate)
				}

			},

			getCategoriesCount(categories) {
				const promises = categories.map(async c => {
					const res = await this.$request.requestAsync(this.host + 'api/v1/blogs/category/count/' + c
						.id);
					return res.data;
				});
				Promise.all(promises).then(results => {
					const newCategories = results.map((count, index) => {
						return {
							id: categories[index].id,
							name: categories[index].name,
							count: count.data ? count.data : 0
						};
					});
					this.categories = newCategories;
					this.status[1].visible = this.categories.length > 0;

				});
			},

			getTags() {
				this.myTags = []
				this.$request.get(this.host + '/api/v1/tags/', res => {
					res.data.forEach(async (r, index) => {
						let data = await this.$request.requestAsync(this.host + 'api/v1/tags/count/' +
							r.id)
						let tag = {
							id: res.data[index].id,
							name: res.data[index].name,
							count: data.data.data
						}
						this.myTags.push(tag)
					})

				})
			},
			clickSwitch(index) {
				let now = this.status[index].visible
				this.status[index].visible = !now
			},
			clickAddName() {
				this.$refs.add_shell.show()
			},
			clickUpdate(id, name) {
				updateId = id
				this.oldName = name
				this.$refs.update_shell.show()
			},
			clickAddNameTag() {
				this.$refs.add_tag_shell.show()
			},
			clickUpdateTag(id, name) {
				updateTagId = id
				this.oldNameTag = name
				this.$refs.update_tag_shell.show()
			},
			clickLogin() {
				if (this.token == null) {
					this.$refs.login.show()
				}
			},
			clickDelete(count, id, type) {
				if (count != 0) {
					return
				}
				uni.showModal({
					title: '删除',
					content: '你确定删除吗',
					success: res => {
						if (res.confirm) {
							let url = type == 0 ? this.host + 'api/v1/categories/delete/' + id : this.host +
								'api/v1/tags/delete/' + id
							console.log(url);
							this.$request.deleteParams(url, {
								"token": this.token
							}, res => {
								if (res.success) {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});

									if (type == 0) {
										let index = this.categories.indexOf(id)
										this.categories.splice(index, 1)
										uni.setStorageSync(categoriess, this.categories)
									} else {
										let index = this.myTags.indexOf(id)
										this.categories.splice(index, 1)
									}
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});

								}
							}, () => {}, () => {})
						}

					},
					fail: () => {},
					complete: () => {}
				});

			},
			clickLogout() {
				uni.showModal({
					title: '注销',
					content: '你确定注销吗',
					success: res => {
						let data = {
							"token": this.token
						}
						if (res.confirm) {
							uni.showLoading({
									title: '注销中……',
									mask: false
								}),
								this.$request.postParams(this.host + 'api/v1/logout', data, res => {
										uni.showToast({
											title: res.message,
											icon: 'none'
										})
										uni.removeStorageSync(this.$params.user)
										this.avatar = "../../static/icons/ic_mine.png"
										this.name = "点击登录"
										this.email = ""
										this.role = "游客"
										this.token = null
										this.type = -1
										user = {}
										this.myGoodsBlogs = []
										this.myBlogs = []
										this.myCount = -1
										page = 0
										this.status.visible = false
									}, () => {},
									() => {})
						} else if (res.cancel) {
							return
						}

					},
					fail: () => {},
					complete: () => {}
				})
			},
			confirmAdd() {
				if (!this.newName) {
					return
				}
				let url = this.host + 'api/v1/categories/add'
				let data = {
					"token": this.token,
					"name": this.newName
				}
				this.$request.requestAsync(url, data, 'POST')
					.then(res => {
						console.log(res);
						if (!res.data.success) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							this.newName = ''
							this.$refs.add_shell.clickToHide()
						} else {
							let category = {
								id: res.data.data.id,
								name: res.data.data.name,
								count: 0
							}
							this.categoriess.push(category)
							this.newName = ''
							this.$refs.add_shell.clickToHide()
						}
					})
					.catch(err => {
						console.log(err);
					})
			},

			confirmAddTag() {
				if (!this.newNameTag) {
					return
				}
				let url = this.host + 'api/v1/tags/add'
				let data = {
					"token": this.token,
					"name": this.newNameTag
				}
				this.$request.requestAsync(url, data, 'POST')
					.then(res => {
						console.log(res);
						if (!res.data.success) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							this.newName = ''
							this.$refs.add_tag_shell.clickToHide()
						} else {
							let category = {
								id: res.data.data.id,
								name: res.data.data.name,
								count: 0
							}
							this.categoriess.push(category)
							this.newNameTag = ''
							this.$refs.add_tag_shell.clickToHide()
						}
					})
					.catch(err => {
						console.log(err);
					})
			},

			confirmUpdate() {
				if (!this.oldName) {
					return
				}
				let url = this.host + 'api/v1/categories/put/' + updateId
				let data = {
					"token": this.token,
					"name": this.oldName
				}
				this.$request.requestAsync(url, data, 'PUT')
					.then(res => {
						console.log(res);
						if (!res.data.success) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							this.$refs.update_shell.clickToHide()
						} else {

							this.categoriess.forEach(c => {
								if (c.id == res.data.data.id) {
									c.name = res.data.data.name
								}
							})
							this.$refs.add_shell.clickToHide()
						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			confirmUpdateTag() {
				if (!this.oldNameTag) {
					return
				}
				let url = this.host + 'api/v1/tags/put/' + updateTagId
				let data = {
					"token": this.token,
					"name": this.oldNameTag
				}
				this.$request.requestAsync(url, data, 'PUT')
					.then(res => {
						console.log(res);
						if (!res.data.success) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							this.$refs.update_tag_shell.clickToHide()
						} else {

							this.myTags.forEach(c => {
								if (c.id == res.data.data.id) {
									c.name = res.data.data.name
								}
							})
							this.$refs.update_tag_shell.clickToHide()
						}
					})
					.catch(err => {
						console.log(err);
					})
			},

			afterLogin() {
				if (this.token) {
					return
				}
				user = uni.getStorageSync(this.$params.noti_refresh_user)
				this.token = user.token
				this.avatar = this.host + user.avatar
				this.name = user.nickName
				this.email = user.email
				this.type = user.type
				if (this.type == 0) {
					this.role = "管理员"
					this.badge = "../../static/icons/badge0.png"
				} else if (this.type == 1) {
					this.role = "认证博主"
					this.badge = "../../static/icons/badge1.png"
				} else if (this.type == 2) {
					this.role = "博客会员"
					this.badge = "../../static/icons/badge2.png"
				}
				this.loadData()
			}

		}
	}
</script>

<style>
	@import url("profile.css");
</style>